package com.bsdsma.visonManagementSystemapp.filter;

import com.bsdsma.visonManagementSystemapp.constants.TokenConstants;
import com.bsdsma.visonManagementSystemapp.jwt.JwtUtils;
import com.bsdsma.visonManagementSystemapp.utils.RedisMockUtils;
import com.bsdsma.visonManagementSystemapp.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 登录状态校验
 */
@WebFilter(urlPatterns = "/api/*")
@Slf4j
public class TokenFilter implements Filter {

    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    // 带有此关键字接口不校验登录
    private static final String NO_AUTH_KEY = "/noauth/";
    private static final String[] SKIP_PATHS = new String[]{
            "/api/auth/login",
            "/api/auth/register",
    };
    private static final String METHOD_OPTIONS = "OPTIONS";

    private void handleCors(String origin, HttpServletResponse response) {
        response.addHeader("Access-Control-Allow-Origin", origin);
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,PATCH,OPTIONS");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length,Authorization,authorization,Accept,X-Requested-With,Access-Control-Allow-Methods,Access-Control-Allow-Origin,ct");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        log.info("拦截到请求：{}, Method: {}", requestURI, method);
        String origin = request.getHeader("Origin");
        this.handleCors(origin, response);
        if (Objects.requireNonNull(request.getMethod()).matches(METHOD_OPTIONS)) {
            filterChain.doFilter(request, response);
            return;
        }

        if(this.check(requestURI)){
            log.info("本次请求{}不需要处理", requestURI);
            filterChain.doFilter(request, response);
            return;
        }

        String token = request.getHeader(TokenConstants.AUTHORIZE_TOKEN);
        if(!StringUtils.isBlank(token)){
            try{
                Long uid = JwtUtils.getId(token);
                String realToken = RedisMockUtils.getUserToken(uid);
                if(token.equals(realToken)){
                    request.setAttribute(TokenConstants.UID, uid);
                    filterChain.doFilter(request, response);
                }
            }catch (Exception e){
                log.error(e.getMessage(), e);
            }
        }

        response.setStatus(HttpStatus.UNAUTHORIZED.value());
    }

    public boolean check(String requestURI) {
        if(requestURI.contains(NO_AUTH_KEY)){
            return true;
        }
        for (String url : SKIP_PATHS) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
